﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Flower.SqlServer.Directory.DbGenerator.Generators
{
    internal static class Helper
    {
        private static readonly string SpecificSelectTemplate;
        private static readonly string GeneralSelectTemplate;

        static Helper()
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".SpecificSelect.sql")))
            {
                SpecificSelectTemplate = reader.ReadToEnd();
            }

            using (var reader = new StreamReader(executingAssembly.GetManifestResourceStream(Program.ScriptsNamespace + ".GeneralSelect.sql")))
            {
                GeneralSelectTemplate = reader.ReadToEnd();
            }
        }

        private static string GenerateTabs(int tabsCount)
        {
            var tabs = new StringBuilder();

            for (int i = 0; i < tabsCount; i++)
            {
                tabs.Append('\t');
            }

            return tabs.ToString();
        }

        public static string Tabify(string str, string tabs)
        {
            return tabs + str.Replace("\r\n", "\r\n" + tabs);
        }

        public static string GeneralSelect(int tabsCount)
        {
            return Tabify(GeneralSelectTemplate, GenerateTabs(tabsCount));
        }

        public static string SpecificSelects(int tabsCount)
        {
            string tabsStr = GenerateTabs(tabsCount);

            var specificSelects = new StringBuilder();
            bool isFirst = true;

            foreach (EntriesDefinition.EntryDefinition entryDefinition in EntriesDefinition.Entries)
            {
                string select;

                if (entryDefinition.SpecificColumns != null && entryDefinition.SpecificColumns.Values.Any(col => !col.DontGenrateInsertUpdate))
                {
                    var selectBuilder = new StringBuilder(Tabify(SpecificSelectTemplate, "\t" + tabsStr));

                    select =
                        selectBuilder
                            .Replace
                            (
                                "/*--SpecificColumns--*/",
                                string.Join
                                (
                                    string.Concat(",\n", tabsStr ,"\t\t"),
                                    entryDefinition
                                        .SpecificColumns
                                        .Where(col => !col.Value.DontGenrateInsertUpdate)
                                        .Select(col => string.Concat("[", col.Key, "]"))
                                )
                            )
                            .Replace("/*--EntityName--*/", entryDefinition.Name)
                            .ToString();
                }
                else
                {
                    select = Tabify(GeneralSelectTemplate, "\t" + tabsStr);
                }

                specificSelects.AppendFormat
                (
                    "\n{0}{1}IF @Type = {2}\n{3}",
                    tabsStr,
                    (isFirst) ? string.Empty : "ELSE ",
                    entryDefinition.DirectoryEntryType,
                    select
                );

                isFirst = false;
            }

            specificSelects.AppendFormat("\n{0}ELSE\n{0}\tRETURN 2", tabsStr);

            return specificSelects.ToString();
        }
    }
}
